package com.augurit.gzcgwsp.exchangeOtherData.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import sun.misc.BASE64Encoder;

import com.augurit.common.syslog.tool.SysTraceLogWriter;
import com.augurit.common.system.service.org.IOmOrgService;
import com.augurit.common.system.service.org.IOmUserService;
import com.augurit.common.system.web.org.form.OmUserForm;
import com.augurit.gzcgwsp.commonex.util.lang.DateUtilsEX;
import com.augurit.gzcgwsp.exchangeOtherData.dao.InteriorDao;
import com.augurit.gzcgwsp.exchangeOtherData.entity.InteriornetData;
import com.augurit.gzcgwsp.exchangeOtherData.service.IInteriornetDataService;
import com.augurit.gzcgwsp.sendNotice.foresee.gzcgw.webservice.util.WSInvoker;
import com.foresee.spiderweb.console.security.bean.ServiceResult;



/**
 * 和内门户网站的数据交换
 * @author 张军
 *
 */
@Service
@Transactional
public class InteriornetServiceImpl implements IInteriornetDataService{
	@Autowired
	private InteriorDao interiornetDao;
	@Autowired
	private IOmOrgService omOrgService;
	@Autowired
	private IOmUserService omUserService;
	private static final Logger log=Logger.getLogger(InteriornetServiceImpl.class);
	/**
	 * 主要待办查询的sql
	 * @param status
	 * @param flag 是否过滤是否发送到内门户
	 * @return
	 */
	private String baseDbSql(boolean flag){
		StringBuffer sb=new StringBuffer();
		sb.append("select * from (");
		sb.append(" select distinct inst.wf_bus_instance_id ,hist.create_ as aa,hist.assignee_ as assignee_,\r ");
		sb.append(" hist.dbid_ as bb, temp.template_name , type.template_type_name, \r");
		sb.append("inst.bus_memo1, procinst.id_ as procdbid,procinst.process_duedate,\r");
		sb.append(" inst.bus_date1 , inst.bus_date2,inst.bus_memo3 from jbpm4_hist_task hist,\r");
		sb.append(" jbpm4_hist_procinst procinst, wf_bus_instance inst, wf_bus_template temp, wf_bus_template_type type \r");
		sb.append(" where hist.procinst_=procinst.id_ and  procinst.id_=inst.proc_inst_id and inst.template_id=temp.id and \r");
		sb.append(" temp.template_type_id=type.id and ");
		sb.append("procinst.state_='active'   and \r");
		if(flag){
			sb.append("  hist.state_='open' )t inner join interiornet_data datas on datas.acceptno=t.bus_memo3 \r");
		}else{
			sb.append("  hist.state_='open' )t left join interiornet_data datas on datas.acceptno=t.bus_memo3 \r");
			
		}
		sb.append(" and datas.user_name=t.assignee_ and datas.procinst_id=t.procdbid  \r");
		if(flag){
			sb.append(" and datas.is_send is null");
			sb.append(" and datas.datasts='1'");
		}
		return sb.toString();
	}
	
	/**
	 * 主要已办或办结查询的sql
	 * @param status
	 * @param flag 是否是插入内门户数据交换表
	 * @return
	 */
	private String baseYbSql(String status,boolean flag){
		StringBuffer sb=new StringBuffer();
		sb.append(" select * from (");
		sb.append(" select distinct inst.wf_bus_instance_id , temp.template_name, \r ");
		if("yb".equals(status)){
			sb.append(" task.create_ as aa,task.dbid_ as bb ,type.template_type_name ,inst.bus_memo1,inst.bus_memo3,task.assignee_, \r");
		}else{
			sb.append(" type.template_type_name ,inst.bus_memo1,inst.bus_memo3, \r");
		}
		
		sb.append(" procinst.dbid_ ,inst.bus_date1 , inst.bus_date2 ,procinst.start_ \r");
		sb.append(" ,procinst.id_ as procdbid,procinst.process_duedate \r");
		sb.append(" from jbpm4_hist_task task, jbpm4_hist_procinst procinst, wf_bus_instance inst,  \r");
		sb.append(" wf_bus_template temp, wf_bus_template_type type  \r");
		sb.append("  where task.procinst_=procinst.id_ and procinst.id_=inst.proc_inst_id and \r");
		sb.append(" inst.template_id=temp.id and temp.template_type_id=type.id ");
		if("yb".equals(status)){
			sb.append("and procinst.state_='active' and \r");
		}else{
			sb.append("and procinst.state_='ended' and \r");
		}
		
		sb.append("  task.state_='completed' \r");
		sb.append("order by procinst.start_ desc");
		if(flag){
			sb.append(" ) t inner join  interiornet_data datas on datas.acceptno=t.bus_memo3 \r");
		}else{
			sb.append(" ) t left join  interiornet_data datas on datas.acceptno=t.bus_memo3 \r");
		}
		if("yb".equals(status)){
			sb.append(" and datas.user_name=t.assignee_ and datas.procinst_id=t.procdbid  \r");
		}else{
			sb.append(" and  datas.procinst_id=t.procdbid  \r");
		}
		
		sb.append(" and datas.is_send is null ");
		if("yb".equals(status)){
			sb.append(" and datas.datasts='2'");
		}else{
			sb.append(" and datas.datasts='3'");
		}
		return sb.toString();
	}
	
	/**
	 * 
	 * @param element
	 * @param status
	 */
	private boolean  getData(Element element,String status){
		String sql=null;
		if("db".equals(status)){
			 sql=baseDbSql(true);	
		}else if("yb".equals(status)){
			 sql=baseYbSql("yb",true);
		}else{
			 sql=baseYbSql("bj",true);
		}
		log.info("sql =     = "+sql);
		List list=this.interiornetDao.queryForList(sql);
		log.info("list.size() =     = "+list.size());
		if(list.size()>0){
			this.getDataByStatus(element,list, status);
			return true;
		}
		else
			return false;
	}
	
	/**
	 * 查询哪些人办理过
	 * @param dbid
	 * @return
	 */
	private List getUsers(String procinstId){
		String sql="select s.assignee_,s.activity_chinese_name,s.end_ from jbpm4_hist_task s where s.dbid_ not in( \r";
			   sql+=" select t.dbid_ from jbpm4_hist_task t ,jbpm4_hist_task tb \r";
			   sql+=" where t.dbid_<>tb.dbid_ and t.assignee_=tb.assignee_ and \r";
			   sql+="  t.activity_chinese_name=tb.activity_chinese_name  and t.state_=tb.state_ \r";
			   sql+=" and t.procinst_=tb.procinst_  and  t.procinst_='"+procinstId+"' \r";
			   sql+="  and t.state_='completed' ) and  s.procinst_='"+procinstId+"' and  s.state_='completed'";
			   sql = "select t.assignee_, t.activity_chinese_name, t.end_ from JBPM4_HIST_TASK t where t.procinst_='"+procinstId+"' and t.state_='completed'  order by t.end_ asc";
			   log.info("allUserSql = "+sql);
		List list=this.interiornetDao.queryForList(sql);
		return list;
	}
	
	/**
	 * 获取当前环节
	 * @param procinstId
	 * @return
	 */
	private String getCurrent(String procinstId){
		String sql=" select t.activity_chinese_name from jbpm4_hist_task t where  t.procinst_='"+procinstId+"' and t.state_='open'";
		List list=this.interiornetDao.queryForList(sql);
		if(list.size()>0){
			Map map=(Map) list.get(0);
			return (String) map.get("activity_chinese_name"); 
		}
		return null;
	}
	
	/**
	 * 根据所有人的待办已办生成xml
	 * @return
	 */
	private void getDataByStatus(Element element,List list,String status){
		Locale locale = Locale.getDefault(); 
		ResourceBundle localResource = ResourceBundle.getBundle("interfaceExchange", locale); 
		String url = localResource.getString("fxurl");
		if(list.size()>0){
			for(int i=0;i<list.size();i++){
				Map map=(Map) list.get(i);
				String username=(String) map.get("assignee_");
				String instid=(String)map.get("wf_bus_instance_id");
				String dbid=(String)map.get("bb");
				log.info("dbid----------------------"+dbid);
				String procinstId=(String)map.get("procdbid");//已办的时候需要查询那些人办理过
				String tempname=(String)map.get("template_name");//承办业务
				String typename=(String)map.get("template_type_name");//业务类别
				String bus_date2=(String)map.get("bus_date2");//收案时间
				String acceptno=(String)map.get("bus_memo3");//受理号
				String sqdw=(String)map.get("bus_memo1");//申请单位
				log.info("sqdw----------------------"+sqdw);
				String finish_date=(String)map.get("process_duedate");//结案日期
				String current=(String)map.get("acvity_name");//环节名称
				if(StringUtils.isNotBlank(finish_date)){
					SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
					try {
						Date date=sdf.parse(finish_date);
						finish_date=sdf.format(date);
					} catch (ParseException e) {
						e.printStackTrace();
					}
					
				}
				if(StringUtils.isNotBlank(bus_date2) && bus_date2.length()>=10){
					bus_date2=bus_date2.substring(0,10);
				}
				Element item=null;
				if("db".equals(status)){
					Element user=element.addElement("user");	
					user.addAttribute("login_name",username==null?"":username);
					item=user.addElement("item");
					this.upDbData(username, current, acceptno);
				}else if("yb".equals(status)){
					if(i==0){//只需要一个item
						item=element.addElement("item");
					}else{
						item=element.addElement("item1");
					}
					this.updateYbData("yb",username, current, acceptno);
				}else{
					item=element.addElement("item");
					this.updateYbData("bj",username, current, acceptno);
				}
				item.addElement("create_date").addText(DateUtilsEX.dateFormate(new Date(), "yyyy-MM-dd HH:mm:ss"));
				if("db".equals(status)){//待办放jbpm4_hist_task表的dbid_
					item.addElement("id").addText(dbid==null?"":dbid);
				}else{//已办和办结放WF_BUS_INSTANCE表的WF_BUS_INSTANCE_ID
					item.addElement("id").addText(instid==null?"":instid);
				}				
				item.addElement("status").addText("");
				item.addElement("number").addText(acceptno==null?"":acceptno);
				item.addElement("type").addText(typename==null?"":typename);
				item.addElement("business").addText(tempname.replace(">", ""));
				item.addElement("apply_unit").addText(sqdw);
				if(!"bj".equals(status)){//不是已结
					item.addElement("current").addText(current);
				}
				
				item.addElement("receive_date").addText(bus_date2);
				item.addElement("finish_date").addText(finish_date==null?"":finish_date);
				if("db".equals(status)){
					item.addElement("link").addText(url+"/wf/wf-ex!signTask.action?instance.taskInstDbid="+dbid);
					
				}else if("yb".equals(status)){
					item.addElement("link").addText(url+"/wf/wf-ex!viewTask.action?instance.wfBusInstanceId="+instid+"&instance.viewName=yb");
				}else{
					item.addElement("link").addText(url+"/wf/wf-ex!viewTask.action?instance.wfBusInstanceId="+instid+"&instance.viewName=bj");
				}
				if(!"db".equals(status)){//已办和办结都需要
					Element user_set=item.addElement("user_set");
					List users=this.getUsers(procinstId);
					if(users.size()>0){
						for(int k=0;k<users.size();k++){
						  Map usermap=(Map) users.get(k);
						  String ybname=(String)usermap.get("assignee_");
						  String actname=(String)usermap.get("activity_chinese_name");
						  String completetime=(String)usermap.get("end_");
					 	  if(StringUtils.isNotBlank(completetime)){
							SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
							try {
								Date date=sdf.parse(completetime);
								completetime=sdf.format(date);
							} catch (ParseException e) {
								log.error("文件错误"+e);
								
							}	
						 }
						  Element user=user_set.addElement("user");
						  user.addElement("login_name").addText(ybname);
						  user.addElement("step").addText(actname);
						  user.addElement("handle_time").addText(completetime);
					    }
					}
				}
			
			}
		}
		
	}
	
	/**
	 * 生成xml
	 * @param status
	 * @return
	 */
	public  Document createDoc(String status) {   
	   Document doc = DocumentHelper.createDocument();   
        Element root = doc.addElement("exchange_data");   
        Element head = root.addElement("head");   
        head.addElement("sender").addText("000003"); 
        Element receivers = head.addElement("receivers"); 
        receivers.addElement("receive").addText("000007"); 
        head.addElement("sn").addText(""); 
        if("db".equals(status)){
            root.addElement("businessCode").addText("11_DB"); 
        }else if("yb".equals(status)){
        	head.addElement("businessCode").addText("12_YB"); 
        }else{
        	head.addElement("businessCode").addText("13_Bj"); 
        }
   
        head.addElement("sendTime").addText(DateUtilsEX.dateFormate(new Date(), "yyyy-MM-dd HH:mm:ss"));
        Element body = root.addElement("body");   
        Element RecordData = body.addElement("RecordData");   
        Element UnitData = RecordData.addElement("UnitData");   
        UnitData.addElement("UnitIDName").addText("time");   
        UnitData.addElement("UnitValue").addText(DateUtilsEX.dateFormate(new Date(), "yyyy-MM-dd HH:mm:ss"));   
        Element UnitData2 = RecordData.addElement("UnitData"); 
        if("db".equals(status)){
        	 UnitData2.addElement("UnitIDName").addText("db_table");  
        }else if("yb".equals(status)){
        	 UnitData2.addElement("UnitIDName").addText("yb_table");  
        }else{
        	 UnitData2.addElement("UnitIDName").addText("bj_table");  
        }
        Element UnitValue2 = UnitData2.addElement("UnitValue"); 
        Element db_table2=null;
        if("db".equals(status)){
        	 db_table2 = UnitValue2.addElement("db_table");  
       }else if("yb".equals(status)){
    	    db_table2 = UnitValue2.addElement("yb_table");  
       }else{
    	    db_table2 = UnitValue2.addElement("yj_table");  
       }
        if(getData(db_table2,status)){
        	
        	return doc;
        }
        else 
        	return null;
	   }   
	
	/**
	 * 获取路径如果不存在路径就去当前环境下的路径
	 * @param filename
	 * @return
	 */
	private String getPath(String filename){
		 String path=null;
		try {
			String context = new File(getClass().getClassLoader().getResource("").toURI()).getPath();
			 context=context.substring(0,context.indexOf("WEB-INF")-1);
			 Locale locale = Locale.getDefault(); 
			 ResourceBundle localResource = ResourceBundle.getBundle("interfaceExchange", locale); 
			 String datapath = localResource.getString("fxdatapath");
			
			 if(!new File(datapath).exists()){
				 path = context+"/exchangeotherdata/"+filename;
			 }else{
				 path=datapath+File.separator+filename;
			 }
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		path=path.replace("/", File.separator);
		return path;
	}
	
	
	/**
	 * 获取文件名称
	 * @param suffix
	 * @return
	 */
	private String getFilename(String suffix){
		   String formatDateX = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			//int randomX = new Random().nextInt(10000);
			String filename =formatDateX+"."+suffix;
			return filename;
	}
	
	
	/**
	 * 创建待办
	 */
	public void createDbDoc(){
		 try {
			 String filename=this.getFilename("xml");
			 String path=this.getPath("db_"+filename);
			 log.info("path===="+path);
			 Document doc = this.createDoc("db");  
			 if(doc!=null){
				OutputFormat format = OutputFormat.createPrettyPrint();   
				format.setEncoding("UTF-8");  
				FileOutputStream fos = new FileOutputStream(path);      
				XMLWriter writer = new XMLWriter(fos, format);
				//writer.setEscapeText(false); 
			    writer.write(doc);   
				writer.close();
			 }
		
		}  catch (Exception e) {
			e.printStackTrace();
		}   
	}
	/*
	 * (non-Javadoc)
	 * @see com.augurit.gzcgwsp.exchangeOtherData.service.IInteriornetDataService#createYbDoc()
	 */
	public void createYbDoc(){
		 try {
			 String filename=this.getFilename("xml");
			 String path=this.getPath("yb_"+filename);
			 Document doc = this.createDoc("yb"); 
			 if(doc!=null){
				OutputFormat format = OutputFormat.createPrettyPrint();   
				format.setEncoding("UTF-8");  
				FileOutputStream fos = new FileOutputStream(path);      
				XMLWriter writer = new XMLWriter(fos, format);    
				//writer.setEscapeText(false); //不转义
			    writer.write(doc);   
				writer.close();
			 }
		}  catch (Exception e) {
			e.printStackTrace();
		}   
	}
	/*
	 * (non-Javadoc)
	 * @see com.augurit.gzcgwsp.exchangeOtherData.service.IInteriornetDataService#createDbDoc()
	 */
	public void createBjDoc(){
		 try {
			 String filename=this.getFilename("xml");
			 String path=this.getPath("yj_"+filename);
			 Document doc = this.createDoc("bj");   
			 if(doc!=null){
				OutputFormat format = OutputFormat.createPrettyPrint();   
				FileOutputStream fos = new FileOutputStream(path);      
				XMLWriter writer = new XMLWriter(fos, format);    
				//writer.setEscapeText(false); 
			    writer.write(doc);   
				writer.close(); 
			 }
	
		}  catch (Exception e) {
			e.printStackTrace();
		}   
	}

	@Override
	/**
	 * 网内门户表插入数据
	 */
	public void insertDbData() {
		String sql=this.baseDbSql(false);
		List list=this.interiornetDao.queryForList(sql);
		if(list.size()>0){
			for(int k=0;k<list.size();k++){
				Map map=(Map) list.get(k);
				String username=(String) map.get("assignee_");
				String procinstId=(String)map.get("procdbid");//已办的时候需要查询那些人办理过
				String acceptno=(String)map.get("bus_memo3");//受理号
				String instanceId=(String) map.get("wf_bus_instance_id");
				String current=this.getCurrent(procinstId);
				String dbid_ = (String)map.get("bb");//
				String createTime = (String)map.get("aa");//jbpm4_hist_task表的create_,如果InteriornetData表中有相同记录，
													   //但是create_不同，则插入一条待办
				log.info("aa ====== "+createTime);
				String hql=" from InteriornetData where userName='"+username+"'" +
						" and acceptno='"+acceptno+"'"+" and acvityName='"+current+"' and datasts='1' order by id desc";
				List data=this.interiornetDao.find(hql);
				if(data.size()<=0){
					InteriornetData entity=new InteriornetData();
					entity.setAcceptno(acceptno);
					entity.setAcvityName(current);
					entity.setSts("1");//未改变状态
					entity.setDatasts("1");//待办
					entity.setUserName(username);
					entity.setInstanceId(Long.valueOf(instanceId));
					entity.setProcinstId(procinstId);
					entity.setCreateTime(createTime);
					entity.setDbid_(dbid_);
					this.interiornetDao.save(entity);
				}else{//InteriornetData表中有相同记录，判断createTime是否与jbpm4_hist_task表的create_相同，不同，则插入一条待办					
					InteriornetData interiornetData = (InteriornetData)data.get(0);
					log.info("bb ====== "+interiornetData.getCreateTime());
					if(!createTime.equals(interiornetData.getCreateTime())){//create_不同，则插入一条待办
						InteriornetData entity=new InteriornetData();
						entity.setAcceptno(acceptno);
						entity.setAcvityName(current);
						entity.setSts("1");//未改变状态
						entity.setDatasts("1");//待办
						entity.setUserName(username);
						entity.setInstanceId(Long.valueOf(instanceId));
						entity.setProcinstId(procinstId);
						entity.setCreateTime(createTime);
						entity.setDbid_(dbid_);
						this.interiornetDao.save(entity);
					}
				}
			}
		}
	}

	@Override	
	public void insertBjData() {
		String sql=this.baseYbSql("bj",false);
		List list=this.interiornetDao.queryForList(sql);
		if(list.size()>0){
			for(int k=0;k<list.size();k++){
				Map map=(Map) list.get(k);
				String username=(String) map.get("assignee_");
				String procinstId=(String)map.get("procdbid");//已办的时候需要查询那些人办理过
				String acceptno=(String)map.get("bus_memo3");//受理号
				String instanceId=(String) map.get("wf_bus_instance_id");
				String current=this.getCurrent(procinstId);
				String createTime = (String)map.get("aa");//jbpm4_hist_task表的create_,如果InteriornetData表中有相同记录，
				   //但是create_不同，则插入一条待办
				String hql=" from InteriornetData where " +
						"  acceptno='"+acceptno+"'"+" and datasts='3'  order by id desc";
				List data=this.interiornetDao.find(hql);
				if(data.size()<=0){
					InteriornetData entity=new InteriornetData();
					entity.setAcceptno(acceptno);
					entity.setAcvityName(current);
					entity.setSts("1");//未改变状态
					entity.setDatasts("3");//已结
					entity.setUserName(username);
					entity.setInstanceId(Long.valueOf(instanceId));
					entity.setProcinstId(procinstId);
					entity.setCreateTime(createTime);
					this.interiornetDao.save(entity);
				}
			}
		}
		
	}

	@Override
	public void insertYbData() {
		String sql=this.baseYbSql("yb",false);
		List list=this.interiornetDao.queryForList(sql);
		if(list.size()>0){
			for(int k=0;k<list.size();k++){
				Map map=(Map) list.get(k);
				String username=(String) map.get("assignee_");
				String procinstId=(String)map.get("procdbid");//已办的时候需要查询那些人办理过
				String acceptno=(String)map.get("bus_memo3");//受理号
				String instanceId=(String) map.get("wf_bus_instance_id");
				String current=this.getCurrent(procinstId);
				String dbid_=(String) map.get("bb");
				log.info("已办工作流表dbid_ ====== "+dbid_);
				String createTime = (String)map.get("aa");//jbpm4_hist_task表的create_,如果InteriornetData表中有相同记录，
				   //但是create_不同，则插入一条待办
				
				String hql=" from InteriornetData where userName='"+username+"'" +
						" and acceptno='"+acceptno+"'"+" and datasts='2' and dbid_='"+dbid_+"' order by id desc";
				List data=this.interiornetDao.find(hql);
				if(data.size()<=0){
					InteriornetData entity=new InteriornetData();
					entity.setAcceptno(acceptno);
					entity.setAcvityName(current);
					entity.setSts("1");//未改变状态
					entity.setDatasts("2");//已办
					entity.setUserName(username);
					entity.setInstanceId(Long.valueOf(instanceId));
					entity.setProcinstId(procinstId);
					entity.setDbid_(dbid_);
					entity.setCreateTime(createTime);
					this.interiornetDao.save(entity);
				}else{//InteriornetData表中有相同记录，判断createTime是否与jbpm4_hist_task表的create_相同，不同，则插入一条待办					
					InteriornetData interiornetData = (InteriornetData)data.get(0);
					log.info("已办工作流表 ====== "+createTime+" acceptNo = "+acceptno);
					log.info("已办数据表 ====== "+interiornetData.getCreateTime()+" acceptNo = "+acceptno);
					if(!createTime.equals(interiornetData.getCreateTime())){//create_不同，则插入一条待办
						InteriornetData entity=new InteriornetData();
						entity.setAcceptno(acceptno);
						entity.setAcvityName(current);
						entity.setSts("1");//未改变状态
						entity.setDatasts("2");//已办
						entity.setUserName(username);
						entity.setInstanceId(Long.valueOf(instanceId));
						entity.setProcinstId(procinstId);
						entity.setDbid_(dbid_);
						entity.setCreateTime(createTime);
//						this.interiornetDao.save(entity);
					}
				}
			}
		}		
	}
	/**
	 * 更新待办的数据状态为发送
	 * @param username
	 * @param acvityName
	 * @param acceptno
	 */
	public void upDbData(String username,String acvityName,String acceptno){
		String hql=" from InteriornetData where userName='"+username+"'" +
		" and acceptno='"+acceptno+"'"+" and acvityName='"+acvityName+"'" +
		"and  isSend is null";
		List data=this.interiornetDao.find(hql);
		if(data.size()>0){
			InteriornetData entity=(InteriornetData) data.get(0);
			entity.setIsSend("1");
			this.interiornetDao.save(entity);
		}
	}
	
	/**
	 *  更新已办的数据状态为发送
	 * @param username
	 * @param acvityName
	 * @param acceptno
	 */
	public void updateYbData(String status,String username,String acvityName,String acceptno){
		String hql=" from InteriornetData " ;
		if("yb".equals(status)){
			hql+=" where userName='"+username+"' and acceptno='"+acceptno+"'"+" and datasts='2'" ;
		}else{
			hql+=" where acceptno='"+acceptno+"'"+" and datasts='3'" ;
		}
		hql+="and  isSend is null";
		List data=this.interiornetDao.find(hql);
		if(data.size()>0){
			InteriornetData entity=(InteriornetData) data.get(0);
			entity.setIsSend("1");
			this.interiornetDao.save(entity);
		}
	}
	/*
	 * (non-Javadoc)
	 * @see com.augurit.gzcgwsp.exchangeOtherData.service.IInteriornetDataService#updateDbdata()
	 */
	@Override
	public void updateDbdata() {
		String sql=" select * from interiornet_data datas,jbpm4_hist_task tbs where \r" +
				" datas.procinst_id=tbs.procinst_ and tbs.assignee_=datas.user_name and \r" +
				"tbs.state_='completed' and tbs.activity_chinese_name=datas.acvity_name and datas.datasts='1' \r" +
				" and datas.sts!='2' and datas.dbid_=tbs.dbid_ \r"; 
		List list=this.interiornetDao.queryForList(sql);
		if(list.size()>0){
			for(int k=0;k<list.size();k++){
				 Map map=(Map) list.get(k);
				 String acceptno=(String) map.get("acceptno");
				 String instance_id=(String) map.get("instance_id");
				 String username=(String) map.get("assignee_");//用户名
				 String acvityName=(String) map.get("acvity_name");//环节名称
				 String signtime=(String) map.get("sign_time");
				 String id = (String) map.get("id");
				 String dbid_ = (String) map.get("dbid_");
				 log.info("id ========================================================================= "+id);
				 //调用内门户接口改变为已办状态
				 Locale locale = Locale.getDefault(); 
				 ResourceBundle localResource = ResourceBundle.getBundle("interfaceExchange", locale); 
				 String url = localResource.getString("interiorneturl");
				 
				 Document doc=DocumentHelper.createDocument();
				 Element feedback=doc.addElement("feedback");
				 feedback.addElement("caseId").addText(dbid_);
				 feedback.addElement("handleStatus").addText("F");
				 feedback.addElement("systemCode").addText("000003");
				 feedback.addElement("handleTime").addText(signtime==null?
						 DateUtilsEX.getDateByDay(new Date(), 0, "yyyy-MM-dd HH:mm:ss"):signtime);
				 String xml=doc.asXML();
				 log.info("加密前xml ========================================================================= "+xml);
				 BASE64Encoder decoder = new BASE64Encoder();
				 try {
					 WSInvoker wsInvoker = new WSInvoker();
					 Object[] obj = new Object[1];
					 obj[0]=new String(decoder.encode(xml.getBytes()));
					 log.info("加密后xml ========================================================================= "+new String(decoder.encode(xml.getBytes())));
					 ServiceResult result=wsInvoker.invokeWS(url, "NBMH_DaiBanFeedBack_Service", "feedBackDaiBanInfo", obj);
					 log.info("serviceResult.getRetMessage() ====== "+result.getRetMessage());
					 //new String(decoder.decodeBuffer(result.toString()), "UTF-8");
					 String retCode=result.getRetCode();
					 //log.error(dbid_+"调用删除待办成功，返回值："+retCode);
					 if("0".equals(retCode)){
						 this.updateChangdataSts(acceptno, username, acvityName, "2",id);
					 }else{
						 this.updateChangdataSts(acceptno, username, acvityName, "3",id);
					 }
				} catch (Exception e) {
					log.error(dbid_+"调用删除待办失败"+SysTraceLogWriter.MESSAGE_SEPARATOR + e.getMessage(),e);
					e.printStackTrace();
				}
			}
		}
	}
	

	
	/**
	 * 更改内门户网站交换数据状态
	 * @param acceptno
	 * @param username
	 * @param acvityName
	 * @param sts
	 */
	private void updateChangdataSts(String acceptno,String username,String acvityName,String sts,String id){
		
//		String hql=" from InteriornetData where userName='"+username+"'" +
//		" and acceptno='"+acceptno+"'"+" and acvityName='"+acvityName+"'" +
//		"and sts='1' and datasts='1'";
//		List data=this.interiornetDao.find(hql);
//		if(data.size()>0){
//			InteriornetData entity=(InteriornetData) data.get(0);
			String sql=" update interiornet_data set sts='"+sts+"' where id="+ id + " and datasts='1'";
			interiornetDao.updateDateBase(sql);
//		}
	}

	@Override
	public String insertOrg(String paramXml) {
		try {
			Document doc=DocumentHelper.parseText(paramXml);
			Element root=doc.getRootElement();   
			String errorCode=getElementValue(root, "errorCode");
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
		
	}

	@Override
	public String insertUser(String paramXml) {
		try {
			Document doc=DocumentHelper.parseText(paramXml);
			Element root=doc.getRootElement();  
			String userCode=getElementValue(root, "userCode");
			String userName=getElementValue(root, "userName");
			String orgCode=getElementValue(root, "orgCode");
			String password=getElementValue(root, "encryptPassword");
			String position=getElementValue(root, "position");
			String sex=getElementValue(root, "sex");
			String telephone=getElementValue(root, "telephone");
			String mobile=getElementValue(root, "mobilePhone");
			String email=getElementValue(root, "email");
			String status=getElementValue(root, "status");
			String createTime=getElementValue(root, "createTime");
			//在机构下增加
			if(orgCode != null){
				 OmUserForm form=new OmUserForm();
				 form.setUserCode(userCode);
				 form.setLoginName(userCode);
				 form.setUserName(userName);
				 if("0".equals(status)){
					 form.setIsActive("1");
				 }else{
					 form.setIsActive("0");
				 }
				 form.setPassword(password);
				 form.setOfficeTel(telephone);
				 form.setMobile(mobile);
				 form.setSex(sex);
				 form.setEmail(email);
				 form.setCreateTime(DateUtilsEX.getStringToDate(createTime,"yyyy-MM-dd"));
				//根节点下新增用户
				if("-1".equals(orgCode)){
					omUserService.save(form);
				}
				//普通机构下新增用户
				else{
					try {
						omUserService.addUserToOrg(form, Long.valueOf(orgCode));
						
						
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
			
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		
		return null;
	}

	/**
	 * 构造内门户网站返回xml
	 * @param retCode
	 * @param message
	 * @return
	 */
	private String resultXml(String retCode,String message){
		Document document=DocumentHelper.createDocument();
		Element root=document.addElement("result");
		root.addElement("retCode").addText(retCode);
		root.addElement("retMessage").addText(message);
		root.addElement("ResponseStatus");
		return document.asXML();
	}
	
	
	/**
	 * 获取某个节点下的所有节点
	 * @param ele
	 * @param name
	 * @return 
	 */
	public static List<Element> getElements(Element ele, String name){
		List nodes = ele.elements(name);   
		return nodes;
	}
	/**
	 * 某个节点下的属性值
	 * @param ele
	 * @param name
	 * @return 
	 */
	public static String getElementValue(Element ele,String name){
		List<Element> list=getElements(ele, name);
		String value="";
		for (Iterator it = list.iterator(); it.hasNext();) {   
			Element elm = (Element) it.next();  
			value=elm.getText().toString();
		}  
		return value;
	}
	
	
	public static void main(String args[]){
		InteriornetServiceImpl service=new InteriornetServiceImpl();
		String xml="<info><userCode>登录帐号</userCode></info>";
		
		service.insertUser(xml);
		
		
	}

}
